const Multipart = require('./Multipart.min.js')
var baseUrl='https://www.oyvvbdev.top/api';
import Notify from "@vant/weapp/notify/notify"
import FormData from "./formdata.js"
import { values } from "mobx-miniprogram";
 const  beforeRequest=(config)=>{
  return config
}
let promise=null
export const login=async()=>{
    if(!promise){
      promise= new Promise(async(resolve,reject)=>{
        const {code}=await new Promise((resolve,reject)=>{
          wx.login({
            success: (res) => {
              resolve(res)
            },
            fail:(res)=>{
              reject(res)
            }
          })
        })
        const app=getApp()
         const {accesstoken,user}=await new Promise((resolve,reject)=>{
           wx.request({
             url: baseUrl+`/accesstoken?code=${code}`,
             method:"post",
             success:res=>{
               resolve(res.data)
             },
             fail:res=>{
               reject(res)
             }
           })
         })
        app.globalData.token = accesstoken;
        app.globalData.userInfo = user;
        wx.setStorageSync("token",accesstoken)
        wx.setStorageSync("userInfo",user)
        promise=null
        resolve()
       })
    }
    return promise
    
}
const beforeSuccess=async (res,config)=>{
  if (res.statusCode===401){
    const app=getApp()
        Notify({
          message:'正在登录中~~',
          type:"warning"
        })
          await login()
          app.globalData.loged=true
          Notify({
            message:'登录成功',
            type:"success"
          })
          return wxRequest(...config)
      
      }else{
        if(res.statusCode===200){
          if(res.data&&res?.data.code===500){
            const app=getApp()
            let userInfo=app.globalData.userInfo    
            if(!userInfo&&!wx.getStorageSync('userInfo')){
              await login()
              userInfo=app.globalData.userInfo
            }else if(!userInfo){
              userInfo=wx.getStorageSync('userInfo')
              app.globalData.userInfo=userInfo
              app.globalData.token=wx.getStorageSync('token')
            }
            if(userInfo.registed===-1){
              wx.navigateTo({
                url: '/pages/user/fitin/fitin',
              })
              return
            }else{
            }
          }
          return res.data
        }else{
          Notify({
            message:res.data.error,
            type:"warning"
          })
          return
  }
  }
}
const beforeFail=(res)=>{
  return res
}
export const wxRequest=async (url,method,data,header)=>{
  const h=header||{'content-type': 'application/json'}
  return new Promise(async(resovle,reject)=>{
    const app=getApp()
    let token=app.globalData.token
    if(!token&&!wx.getStorageSync('token')){
      await login()
      token=app.globalData.token
    }else if(!token){
      token=wx.getStorageSync('token')
      app.globalData.token=token
      app.globalData.useInfo=wx.getStorageSync('userInfo')
    }
    let config={
      url: baseUrl+url,
      method,
      data,
      header:{...h,'Authorization': `Bearer ${token}`},
      success:async res=>{
        resovle(await beforeSuccess(res,[url,method,data]))
      },
      fail:err=>{
        reject(beforeFail(err,[url,method,data]))
      }
    }
    wx.request(config)
  })
}

export const get=async(url,param)=>{
  if(!!param){
    url+="?"+ Object.keys(param)
  .map(key => encodeURIComponent(key) + '=' + encodeURIComponent(param[key]))
  .join('&');
  }
  
  return wxRequest(url,"get",null)
}
export const post=async(url,data)=>{
  return wxRequest(url,"post",data)
}
export const patch=async(url,param,data)=>{
  if(!!param){
    url+="?"+ Object.keys(param)
    .map(key => encodeURIComponent(key) + '=' + encodeURIComponent(param[key]))
    .join('&');
  }
  wxRequest(url,"patch",data)
}
export const remove=async(url,param)=>{
  if(!!param){
    url+="?"+ Object.keys(param)
    .map(key => encodeURIComponent(key) + '=' + encodeURIComponent(param[key]))
    .join('&');
  }
  wxRequest(url,"delete")
}
export const uploadfile=async(url,data,key="",method="post")=>{
  const formData=new FormData()
  for (let k in data){
    if(k===key){
      data[k].forEach(item => {
        formData.appendFile(key,item.tempFilePath)
      });
    }else{
      if(data[k] instanceof Object){
        const obj=data[k]
        for(let k1 in obj){
          formData.append(`${k}.${k1}`,obj[k1])
        }
      }else{
          formData.append(k,data[k])
      }
    }
  }
  const resData=formData.getData()
  const res=await wxRequest(url,method,resData.buffer,{
    'Content-Type': resData.contentType
  })
  return res
}
export const downloadFile=async (url)=>{
  return new Promise((resovle,reject)=>{
    wx.downloadFile({
      url,
      success:(res)=>{  
        if (res.statusCode === 200) {
          resovle(res)
        }else{
          reject(errMsg)
        }
      },
      fail:(err)=>{
        reject(err)
      }
    })
  })
}

